package com.my.storage.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.my.storage.dto.FileDownDTO;
import com.my.storage.exception.error.BusinessException;
import com.my.storage.interceptor.result.Result;
import com.my.storage.model.FileMetadata;
import com.my.storage.service.FileService;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

/**
 * @author xhw
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private static final Logger log = LoggerFactory.getLogger(FileController.class);
    private final FileService fileService;

    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    // 删除指定文件或目录
    @DeleteMapping("/delete")
    public Result<String> deleteFile(
            @RequestParam("path") String path
    ) {

        // 先查询文件元数据
        FileMetadata fileMetadata = fileService.getFileDetails(path);
        if (fileMetadata == null) {
            throw new BusinessException("FILE_NOT_FOUND", "文件未找到");
        }
        //检查没有问题再删除文件
        fileService.deleteFile(path);
        return Result.ok("删除成功");

    }

    // 下载文件
    @GetMapping("/download")
    public ResponseEntity<?> downloadFile(
            @RequestParam("path") String path
    ) {
        FileSystemResource file = fileService.getFileSystemResource(path);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getFilename());

        return ResponseEntity.ok()
                .headers(headers)
                .body(file);

    }

    // 查询指定文件的元数据并提供下载链接
    @GetMapping("/details")
    public Result<FileDownDTO> getFileDetail(
            @RequestParam("path") String path
    ) {

        FileMetadata fileMetadata = fileService.getFileDetails(path);
        FileDownDTO fileDownDTO = new FileDownDTO();
        fileDownDTO.setFileMetadata(fileMetadata);
        //生成下载链接
        String downloadUrl = creatDownloadUrl(path);
        fileDownDTO.setDownloadUrl(downloadUrl);

        return Result.ok(fileDownDTO);
    }

    // 创建下载链接
    public static String creatDownloadUrl(String path) {
        return ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/file/download/")
                .queryParam("path", path)
                .build().toUriString();
    }

    // 查询逻辑路径下的目录以及文件列表
    @GetMapping("/children")
    public Result<List<FileMetadata>> listFiles(
            @RequestParam("path") String path
    ) {
        List<FileMetadata> files = fileService.listChildren(path);
        return Result.ok(files);
    }

    // 上传文件
    @PostMapping("/upload")
    public Result<String> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("path") String path
    ) {
        //实际检测file可以为空但是文件大小是0，稳妥起见还是断言不可以为空
        Assert.notNull(file, "文件不能为空");

        fileService.saveFile(file, path);
        return Result.ok("文件上传成功");

    }
}